package engine.gui.elements;

import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;

import engine.gui.Component;
import engine.util.draw.Draw2D;
import engine.util.texture.TextureLoader;

public class Image extends Component{

	private int texture;
	private int width;
	private int height;
	private int border;
	
	public Image(String path) {
		texture = TextureLoader.loadTexture(path, GL11.GL_NEAREST, GL11.GL_NEAREST, GL13.GL_CLAMP_TO_BORDER, GL13.GL_CLAMP_TO_BORDER, false);
	}
	
	public Image(String path, int width, int height) {
		this(path);
		this.width = width;
		this.height = height;
	}
	
	@Override
	public void render(int x, int y, int width, int height) {
		draw(x, y, width, height);
	}
	
	public int getTexture() {
		return texture;
	}
	
	public void draw(int posX, int posY, int width, int height) {
		if(border == 0) {
			Draw2D.drawImage(texture, posX, posY, width, height);
		} else {
			glBindTexture(GL_TEXTURE_2D, texture);
			
			float b = border / (float) this.width;
			//upper left corner
			Draw2D.drawImage(posX, posY, border, border, 0, 1 - b, b, b);
			
			//upper border
			Draw2D.drawImage(posX + border, posY, width - 2 * border, border, b, 1 - b, 1 - 2 * b, b);
			
			//upper right corner
			Draw2D.drawImage(posX + width - border, posY, border, border, 1 - b, 1 - b, b, b);
			
			//center left border
			Draw2D.drawImage(posX, posY + border, border, height - 2 * border, 0, b, b, 1 - 2 * b);
			
			//center center
			Draw2D.drawImage(posX + border, posY + border, width - 2 * border, height - 2 * border, b, b, 1 - 2 * b, 1 - 2 * b);
			
			//draw center right border
			Draw2D.drawImage(posX + width - border, posY + border, border, height - 2 * border, 1 - b, b, b, 1 - 2 * b);
			
			//lower left corner
			Draw2D.drawImage(posX, posY + height - border, border, border, 0, 0, b, b);
			
			//lower border
			Draw2D.drawImage(posX + border, posY + height - border, width - 2 * border, border, b, 0, 1 - 2 * b, b);
			
			//lower right corner
			Draw2D.drawImage(posX + width - border, posY + height - border, border, border, 1 - b, 0, b, b);
			
			glBindTexture(GL_TEXTURE_2D, 0);
		}
	}
	
	@Override
	public void reset() {
		//do nothing
	}
	
	public int getBorder() {
		return border;
	}
	
	public void setBorder(int border) {
		this.border = border;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
}
